<html>
<head>
    <style>
        #messages {
            text-align: left;
            width: 50%;
            padding: 1em;
            border: 1px solid black;
        }
    </style>
    <link rel="stylesheet" href="CSS/bootstrap.min.css" />
    <meta charset="utf-8" />

    <title>Sample WebSocket Client</title>
</head>
<body>
<div class="container">
    <div id="messages" class="messages"></div>
    <div class="input-fields">
        <p>Type a message and hit send:</p>
        <input id="message"/>
        <button id="send">Send</button>

        <p>Select an image and hit send:</p>
        <input type="file" id="file" accept="image/*"/>

        <button id="sendImage">Send Image</button>
    </div>
</div>
</body>
<script>
    var webSocket = new WebSocket("ws://localhost:4567/broadcast");
    webSocket.onmessage = function (msg) {
        updateChat(msg);
    };
    webSocket.onclose = function () {
        alert("WebSocket connection closed")
    };
    const messageWindow = document.getElementById("messages");

    const sendButton = document.getElementById("send");
    const messageInput = document.getElementById("message");

    const fileInput = document.getElementById("file");
    const sendImageButton = document.getElementById("sendImage");

    webSocket.binaryType = "arraybuffer";


    sendButton.onclick = function (event) {
        sendMessage(messageInput.value);
        messageInput.value = "";
    };

    sendImageButton.onclick = function (event) {
        let file = fileInput.files[0];
        sendMessage(file);
        fileInput.value = null;
    };

    function sendMessage(message) {
        webSocket.send(message);
        addMessageToWindow("Sent Message: " + message);
    }

    function addMessageToWindow(message) {
        messageWindow.innerHTML += `<div>${message}</div>`
    }

    function addImageToWindow(image) {
        let url = URL.createObjectURL(new Blob([image]));
        messageWindow.innerHTML += `<img src="${url}"/>`
    }

    function updateChat(msg) {
        var data = JSON.parse(msg.data);
        insert("chat", data.userMessage);
        id("userlist").innerHTML = "";
        data.userlist.forEach(function (user) {
            insert("userlist", "<li>" + user + "</li>");
        });
    }

    //Helper function for inserting HTML as the first child of an element
    function insert(targetId, message) {
        id(targetId).insertAdjacentHTML("afterbegin", message);
    }

    //Helper function for selecting element by id
    function id(id) {
        return document.getElementById(id);
    }



</script>
<!--<script type="text/javascript" src="JS/jquery-1.9.1.min.js"></script>-->
<script type="text/javascript" src="JS/bootstrap.min.js"></script>

</html>
